package com.baohua.controller;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baohua.exception.BaohuaSystemException;
import com.baohua.model.Dictionary;
import com.baohua.model.DiningTable;
import com.baohua.model.Goods;
import com.baohua.model.Member;
import com.baohua.model.OrderDetails;
import com.baohua.service.MemberService;
import com.baohua.service.OrderService;
import com.baohua.util.StringUtil;

/**
 * 订单类（包括点餐、订单查询、修改订单。。。）
 * @author Happy Everyday
 */
@Controller
@RequestMapping("/order")
public class OrderController {
	
	private OrderService orderService;
	private MemberService memberService;
	
	/**
	 * 根据餐桌种类异步查询餐桌
	 * @param categoryId 餐桌Id
	 * @return 餐桌列表
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/getAllTable", method = RequestMethod.POST)
	@ResponseBody
	public JSONArray getAllDiningTable(@RequestParam("hasBeanSelectedTable") String hasBeanSelectedTable) {
		return orderService.getAllDiningTable(hasBeanSelectedTable);
	}
	
	/**
	 * 修改订单信息:修改订单头信息/删除订单明细/添加订单明细/修改订单明细。
	 * @param 订单内容，JSON格式
	 * @return success 
	 */
	@RequestMapping(value="/modifyOrder", method = RequestMethod.POST)
	@ResponseBody
	public boolean modifyOrder(@RequestParam("modifyMsg") String modifyMsg){
		return orderService.modifyOrder(modifyMsg);
	}
	
	/**
	 * 作废订单
	 * @param orderHeaderId
	 * @return
	 */
	@RequestMapping(value="deprecatedOrder/{orderHeaderId}")
	@ResponseBody
	public boolean deprecateOrder(@PathVariable long orderHeaderId) {
		return orderService.updateOrder(orderHeaderId);
	}
	
	/**
	 * 查看订单详情或者编辑订单信息
	 * @param orderHeader
	 * @param returnJsp
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/showOrOperate/{returnJsp}", method=RequestMethod.GET)
	public String showOrderDetails(@RequestParam("orderHeader") String orderHeader, @PathVariable String returnJsp, Model model) throws UnsupportedEncodingException {
		String path = returnJsp; //"orderDetailsOperate";
		if("orderDetailsUpdate".equals(path)) {//编辑界面需要查询下面的内容
			List<Dictionary> memnCtgis = orderService.findDictionaryByParentCode(StringUtil.MENU_CODE);
			List<Goods> goodsLists = orderService.findAllGoods();
			List<Dictionary> dtnies = orderService.findDictionaryByParentCode(StringUtil.ORDER_CATEGORY_CODE);
			JSONArray jo = JSONArray.fromObject(dtnies);
			model.addAttribute("memnCtgis", memnCtgis);
			model.addAttribute("goodsLists", goodsLists);
			model.addAttribute("dictionaries", jo.toString());
		}
		String orderHeaderStr = new String(orderHeader.getBytes("ISO-8859-1"),"UTF-8");
		List<OrderDetails> lists = orderService.findOrderDetailsByOrderHeaderId(orderHeaderStr);
		
		model.addAttribute("lists", lists);
		model.addAttribute("jsonHeader", orderHeaderStr);
		return path;
	}
	
	/**
	 * 界面初始化，进入订单查询界面
	 * @return
	 */
	@RequestMapping(value="index")
	public String index() {
		return "orderSearch";
	}
	
	/**
	 * 获取查询条件，下拉框的值
	 * @param categoryCode
	 * @return
	 */
	@RequestMapping(value="conditions/{categoryCode}")
	@ResponseBody
	public List<Dictionary> getQueryConditions(@PathVariable String categoryCode) {
		List<Dictionary> dtns = orderService.findDictionaryByParentCode(categoryCode);
		return dtns;
	}
	
	/**
	 * 异步查询订单的列表
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="list")
	@ResponseBody
	public Map listOrder(String orderMsg, HttpServletRequest request) throws UnsupportedEncodingException {
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		int startPost = (page-1) * pageSize;
		
		JSONArray ja = orderService.findListOrderHeader(orderMsg, startPost, pageSize);
		long count = orderService.queryCountOrderHeader(orderMsg);
		Map map = new HashMap();
		map.put("Rows", ja);
		map.put("Total", count);
		return map;
	}
	
	/**
	 * @return 会员明细
	 * @throws BaohuaSystemException 
	 */
	@RequestMapping(value="getMember/{memberNo}", method = RequestMethod.POST)
	@ResponseBody
	public Member getMemberByMemberNo(@PathVariable String memberNo) throws BaohuaSystemException {
		Member member = memberService.queryMemberByMemberNo(memberNo);
		return member;
	}
	
	/**
	 * 确认下单，展示订单明细；
	 * @param orderStr 订单明细
	 * @return orderDetails.jsp
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/showOrderDetails", method = RequestMethod.GET)
	public String listOrder(@RequestParam("orderStr") String orderStr, Model model) throws UnsupportedEncodingException {
		String orderString = new String(orderStr.getBytes("ISO-8859-1"),"UTF-8");
//		String orderCode = UUIDCode.getUUIDCode(StringUtil.ORDER_CODE_PREFIX);
		model.addAttribute("order", orderString);
//		model.addAttribute("code", orderCode);
		return "orderDetails";
	}
	
	/**
	 * 下单
	 * @param 订单内容，JSON格式
	 * @return isSuccess 
	 * @throws UnsupportedEncodingException 
	 * @throws ParseException 
	 */
	@RequestMapping(value="/addOrder", method = RequestMethod.POST)
	@ResponseBody
	public boolean addOrder(@RequestParam("orderStr") String orderStr) throws BaohuaSystemException, UnsupportedEncodingException, ParseException {
		boolean success = false;
		String orderString = new String(orderStr.getBytes("ISO-8859-1"),"UTF-8");
		
		success = orderService.addOrder(orderString);
		return success;
	}

	/**
	 * 根据餐桌种类异步查询餐桌
	 * @param categoryId 餐桌Id
	 * @return 餐桌列表
	 */
	@RequestMapping(value="/showTable/{categoryId}", method = RequestMethod.POST)
	@ResponseBody
	public List<DiningTable> getDiningTableByCategoryId(@PathVariable long categoryId) {
		List<DiningTable> tables = orderService.findDiningTableByCategoryId(categoryId);
		return tables;
	}
	
	/**
	 * 异步查询goods，根据商品种类Id
	 * @param categoryId  商品Id
	 * @return 商品
	 */
	@RequestMapping(value="/showGoods/{categoryId}", method = RequestMethod.POST)
	@ResponseBody
	public List<Goods> getGoodsByCategorisId(@PathVariable long categoryId) {
		List<Goods> goodss = orderService.findDishByGoodsCategory(categoryId);
		return goodss;
	}
	
	/**
	 * 显示点菜界面，包括菜单、餐桌、订单项
	 * @return order.jsp
	 */
	@RequestMapping("/show")
	public String showOrdering(Model model) {
		
		//获取菜的种类，根据菜单种类Code
		List<Dictionary> menuCategories = orderService.findCategoryByCode(StringUtil.MENU_CODE);
		//获取第一个菜
		List<Goods> listGood = orderService.findDishByGoodsCategory(
				menuCategories.get(StringUtil.THE_FIRST_MENU).getDictionaryId());
		
		List<Dictionary> tableCategories = orderService.findCategoryByCode(StringUtil.TABLE_CATEGORY_CODE);
		List<DiningTable> listTable = orderService.findDiningTableByCategoryId(
				tableCategories.get(StringUtil.THE_FIRST_TABLE).getDictionaryId());
		model.addAttribute("categories", menuCategories);
		model.addAttribute("goodss", listGood);
		model.addAttribute("tableCategories", tableCategories);
		model.addAttribute("tables", listTable);
		
		return "order";
	}
	public OrderService getOrderService() {
		return orderService;
	}
	
	@Resource(name="orderService")
	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}
	
	public MemberService getMemberService() {
		return memberService;
	}
	
	@Resource(name="memberService")
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
}
